package core

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/sagoo-cloud/sagooiot/internal/model"
	"github.com/sagoo-cloud/sagooiot/internal/service"
)

func upgradeResultPost(ctx context.Context, _ MQTT.Client, message MQTT.Message) {
	productKey, deviceKey, err := getProductDev(ctx, message.Topic())
	if err != nil {
		return
	}
	productDetail, productDetailErr := service.DevProduct().Get(ctx, productKey)
	if productDetailErr != nil || productDetail == nil {
		g.Log().Errorf(ctx, "find product info error: %v+, topic:%s, message:%s, message ignored", productDetailErr, message.Topic(), string(message.Payload()))
		return
	}
	deviceDetail, err := service.DevDevice().Get(ctx, deviceKey)
	if err != nil {
		g.Log().Errorf(ctx, "find device info error: %v+, topic:%s, message:%s, message ignored", err, message.Topic(), string(message.Payload()))
		return
	}

	v := model.Result{}
	err = json.Unmarshal(message.Payload(), &v)
	if err != nil {
		g.Log().Errorf(ctx, "json.Unmarshal error: %v+, topic:%s, message:%s, message ignored", err, message.Topic(), string(message.Payload()))
		return
	}
	service.UpgradeDevOtaDetail().RecordUpgradeResult(ctx, int(deviceDetail.Id), v.Params.Strategy, v.Params.Version)
}

func getProductDev(ctx context.Context, topic string) (string, string, error) {
	topicInfo := strings.Split(topic, "/")
	if len(topicInfo) != 6 {
		g.Log().Error(ctx, fmt.Sprintf("topic invalid : %s  ", topic))
		return "", "", gerror.New("topic invalid ... ")
	}
	productKey, deviceKey := topicInfo[len(topicInfo)-2], topicInfo[len(topicInfo)-1]
	return productKey, deviceKey, nil
}

func upgradeProcessPost(ctx context.Context, _ MQTT.Client, message MQTT.Message) {
	productKey, deviceKey, err := getProductDev(ctx, message.Topic())
	if err != nil {
		return
	}
	productDetail, productDetailErr := service.DevProduct().Get(ctx, productKey)
	if productDetailErr != nil || productDetail == nil {
		g.Log().Errorf(ctx, "find product info error: %v+, topic:%s, message:%s, message ignored", productDetailErr, message.Topic(), string(message.Payload()))
		return
	}
	deviceDetail, err := service.DevDevice().Get(ctx, deviceKey)
	if err != nil {
		g.Log().Errorf(ctx, "find device info error: %v+, topic:%s, message:%s, message ignored", err, message.Topic(), string(message.Payload()))
		return
	}

	v := model.Result{}
	err = json.Unmarshal(message.Payload(), &v)
	if err != nil {
		g.Log().Errorf(ctx, "json.Unmarshal error: %v+, topic:%s, message:%s, message ignored", err, message.Topic(), string(message.Payload()))
		return
	}
	service.UpgradeDevOtaDetail().RecordUpgradeProcess(ctx, int(deviceDetail.Id), v.Params.Step, v.Params.Strategy)

}
